package com.demo.simpletestapp

import android.content.Context
import android.content.pm.ApplicationInfo
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.util.Log

class AppsUtil {

    val excludedPackages = setOf(
        "com.cadothy.xlive",
        "com.android.dialer",
        "com.cadothy.feedback",
        "com.catos.multiwindow",
        "com.catos.splitscreen",
        "com.android.mms",
        "com.cadothy.gooda",
        "com.qualcomm.qti.qms.service.telemetry",
        "org.codeaurora.dialer",
        "com.android.contacts",
        "com.android.traceur",
        "com.cadothy.userguide"
    )

    /**
     * 获取所有已经安装的应用的包名、应用名、图标、启动界面
     */
    fun getInstalledAppsInfo(context: Context): MutableList<AppInfo> {
        val packageManager: PackageManager = context.packageManager
        val installedAppsInfo: MutableList<AppInfo> = mutableListOf()

        val appsList = packageManager.getInstalledPackages(0)
        var packageName:String
        for (appInfo in appsList) {
            packageName = appInfo.packageName
            if (packageManager.getLaunchIntentForPackage(packageName) != null) {
                if(excludedPackages.contains(packageName)){
                    continue
                }
                Log.d("AppsUtil", "appName:${appInfo.applicationInfo.loadLabel(packageManager).toString()} packageName:${appInfo.packageName} ")
                val appName = appInfo.applicationInfo.loadLabel(packageManager).toString()
                val appIcon = appInfo.applicationInfo.loadIcon(packageManager)

                val launchActivity = getLaunchActivity(packageManager, packageName)
                Log.d("AppsUtil", "getInstalledAppsInfo: launchActivity=${launchActivity}")

                val app = AppInfo(packageName, appName, appIcon, launchActivity)
                installedAppsInfo.add(app)
            }
        }

        return installedAppsInfo
    }


    /**
     * 是否符合规定
     */
    private fun isStandard(appInfo: PackageInfo): Boolean {


        return true
    }

    private fun getLaunchActivity(packageManager: PackageManager, packageName: String): String {
        val intent = packageManager.getLaunchIntentForPackage(packageName)
        return intent?.component?.className ?: ""
    }


//    /**
//     * 获取系统所有安装的应用的包名
//     */
//    private fun getAppInfoList(context: Context): List<AppInfo> {
//        val packageManager = context.packageManager
//        val apps = packageManager.getInstalledApplications(PackageManager.GET_META_DATA)
//        val appList = mutableListOf<AppInfo>()
//        for (app in apps) {
//            val appName = packageManager.getApplicationLabel(app).toString()
//            appList.add(AppInfo(app.packageName, appName,))
//        }
//        return appList
//    }
}